package org.example.jdbc;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ZerlindaLi create at 2021/4/2 17:10
 * @version 1.0.0
 * @description JdbcTemplate
 * 封装所有的处理流程
 */
public abstract class JdbcTemplate {

    private DataSource dataSource;

    public JdbcTemplate(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public final List<?> executeQuery(String sql, RowMapper<?> rowMapper, Object [] values) {
        try{

            // 1. 获取连接
            Connection connection = this.getConnection();
            // 2. 创建语句集
            PreparedStatement pstm = this.getPreparedStatement(connection, sql);
            // 3. 执行语句集
            ResultSet rs = this.executeQuery(pstm, values);
            // 4. 处理结果集
            List<?> result = this.parseResultSet(rs, rowMapper);
            // 5. 关闭结果集
            rs.close();
            // 6. 关闭语句集
            pstm.close();
            // 7. 关闭连接
            connection.close();
            return result;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private List<?> parseResultSet(ResultSet rs, RowMapper<?> rowMapper) throws Exception{
        List<Object> result = new ArrayList<>();
        int rowNum = 0;
        while (rs.next()){
            result.add(rowMapper.mapRow(rs, rowNum++));
        }
        return result;
    }

    private Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    private PreparedStatement getPreparedStatement(Connection connection, String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }

    private ResultSet executeQuery(PreparedStatement pstm, Object [] values) {
        return null;
    }

}

